﻿using Microsoft.IdentityModel.Logging;
using Newtonsoft.Json;
using System.Text;
using WebAPI.Common;

namespace WebAPI.Util
{
    public class RequestLogMiddleWare
    {
        public RequestDelegate next;
        public RequestLogMiddleWare(RequestDelegate _next)
        {
            next = _next;
        }

        public async Task Invoke(HttpContext context)
        {
            try
            {
                //请求地址
                string path = context.Request.Path.Value;
                if (path == "/")
                {
                    await next.Invoke(context);
                    return;
                }

                //排除（第三方）回调接口
                if (path.Contains("/API/Notify/", StringComparison.OrdinalIgnoreCase))
                {
                    await next.Invoke(context);
                    return;
                }

                //请求ip
                string ip = context.Connection.RemoteIpAddress == null ? string.Empty : context.Connection.RemoteIpAddress.ToString();
                if (ip == "::1") { ip = "127.0.0.1"; }

                //请求端口
                int port = context.Connection.RemotePort;

                //请求方式
                string method = context.Request.Method;

                //内容类型
                string contentType = context.Request.ContentType;

                #region JSON数据格式请求
                if (contentType == "application/json")
                {
                    HttpRequest request = context.Request;
                    Stream stream = request.Body;
                    Encoding encdoding = Encoding.UTF8;
                    string responseString = string.Empty;
                    using (StreamReader sr = new StreamReader(stream, encdoding))
                    {
                        responseString = sr.ReadToEndAsync().Result;
                    }
                    //记录日志（“\n”标识换行）
                    //LogUtility.Info($"|请求ip=>{ip}:{port}\n|请求路径=>{path}\n|请求方式=>{method}\n|请求json数据=>{responseString}");
                }
                #endregion

                #region form表单提交请求日志
                if (contentType == "application/x-www-form-urlencoded")
                {
                    //请求Headers数据
                    var headerData = context.Request.Headers.ToList();
                    var headerDataStr = JsonConvert.SerializeObject(headerData);

                    //请求数据
                    var fromDataStr = string.Empty;
                    if (context.Request.ContentLength > 0) //ContentLength==0,context.Request.Form会报错
                    {
                        //请求form表单数据
                        var fromData = context.Request.Form.ToList();
                        fromDataStr = JsonConvert.SerializeObject(fromData);

                        //请求文件数据
                        //string fileStr = string.Empty;
                        //var files = context.Request.Form.Files;
                        //if (files.Count > 0)
                        //{
                        //    foreach (var item in files)
                        //    {
                        //        fileStr += item.FileName + ";";
                        //    }
                        //}
                    }

                    //记录日志（“\n”标识换行）
                    //LogUtility.Info($"|请求ip=>{ip}:{port}\n|请求路径=>{path}\n|请求方式=>{method}\n|请求header数据=>{headerDataStr}\n|form表单数据=>{fromDataStr}");
                }
                #endregion
            }
            catch (Exception ex)
            {
                //LogUtility.Error(ex, "记录请求日志发生错误");
            }

            await next.Invoke(context);
        }
    }
}
